import {
  Card,
  Col,
  Row,
  Button,
  Popover,
  Modal,
  Form,
  Input,
  Popconfirm,
  message,
  Tree,
} from 'antd';
// import SearchTree from '../../../components/SearchTree'
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
// 搜索 表头
import columnsData, { columnsDataType } from './data';
// 模拟的数据
import tableData from '../../mock/tableData';
import React, { useState } from 'react';
import {
  getModelTypeTree,
  addModelType,
  editModelType,
  deleteModelType,
} from '../../services/modelType';

const { Search } = Input;
const { TextArea } = Input;

const ModelType = () => {
  // table 绑定
  const tableRef = React.useRef<ActionType>();
  const [form] = Form.useForm();
  // 新增模态框
  const [isAddInfoModalVisible, setIsAddInfoModalVisible] = useState(false);
  // 正在操作的Id
  const [ModelTypeId, setModelTypeId] = useState('-1');
  // 正在进行的操作
  const [operation, setOperation] = useState('新增');

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 删除提醒 确认
  const confirmDel = async (id: string) => {
    let res = await deleteModelType({ id });
    if (res.code == '000000') {
      message.success('删除成功');
    } else {
      message.error('删除失败');
    }
    tableRef.current?.reload();
  };

  // 删除提醒 取消
  const onCancelDel = () => {
    message.error('取消删除，删除失败');
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0, width: 130 }}>
      <li>
        <a
          onClick={() => {
            setModelTypeId(record.id);
            form.setFieldsValue({});
            setOperation('新增');
            setIsAddInfoModalVisible(true);
          }}
        >
          添加
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a
          onClick={() => {
            setOperation('编辑');
            setModelTypeId(record.id);
            form.setFieldsValue({ ...record });
            setIsAddInfoModalVisible(true);
          }}
        >
          编辑
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <Popconfirm
          className="delPopconfirm"
          title="是否确认删除？"
          okText="是"
          cancelText="否"
          onConfirm={() => confirmDel(record.id)}
          onCancel={onCancelDel}
        >
          <a onClick={() => {}}>删除</a>
        </Popconfirm>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  // 点击新增
  const addInfo = () => {
    form.setFieldsValue({});
    setIsAddInfoModalVisible(true);
  };

  // 添加模型类型
  const add = async () => {
    await form.validateFields();
    let { description, typeCode, typeName } = await form.getFieldsValue();
    let res;
    if (operation == '新增') {
      res = await addModelType({
        description,
        typeCode,
        typeName,
        parentId: ModelTypeId,
      });
    } else {
      res = await editModelType({
        description,
        typeCode,
        typeName,
        id: ModelTypeId,
      });
    }
    if (res.code == '000000') {
      tableRef.current?.reload();
      message.success(`${operation}模型类型成功`);
    } else {
      message.error(`${operation}模型类型失败`);
    }
    setIsAddInfoModalVisible(false);
    form.setFieldsValue({});
    setModelTypeId('-1');
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle="模型类型"
        scroll={{ x: 1000 }}
        actionRef={tableRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          let res = await getModelTypeTree({
            ...params,
            pageNum: params.current,
          });
          console.log(res);

          if (res.code !== '000000') {
            message.error('获取模型管理表格信息失败');
          }
          const result = {
            data: res.data,
            total: res.pagination?.totalSize,
          };
          return result;
        }}
        // defaultData={tableData}
        rowKey="id"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'modelTypeTable',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={addInfo}
          >
            新增
          </Button>,
        ]}
      />
      {/* 增加模态框 */}
      <Modal
        centered
        width={700}
        title={operation}
        open={isAddInfoModalVisible}
        onOk={add}
        onCancel={() => {
          setIsAddInfoModalVisible(false);
        }}
        okText="确定"
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="typeName"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="标识编码"
            name="typeCode"
            rules={[{ required: true, message: '请输入唯一的编码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ModelType;
